

/*
* 对象的比较
* 1.Comparable 接口实现对象的比较
* */

import java.util.Arrays;
import java.util.Comparator;

//Comparable接口实现对象的比较
class A implements Comparable<A> {
    public String name;
    public int age;
    public double sore;

    public A(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public A(String name, int age, double sore) {
        this.name = name;
        this.age = age;
        this.sore = sore;
    }

    @Override
    public int compareTo(A o) {
        if(this.age > o.age) {
            return 1;
        }else if(this.age == o.age) {
            return 0;
        }else {
            return -1;
        }
    }

    @Override
    public String toString() {
        return "A{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sore=" + sore +
                '}';
    }
}
class B {
    public String name;
    public int age;
}
class C {

}

//给一个比较器来比较对象的大小 可以实现以任意属性来比较大小
//通过比较器返回值来判断对象的大小
class AgeComparator implements Comparator<A> {

    @Override
    public int compare(A o1, A o2) {
        return o1.age - o2.age;
    }

}
class SoreComparator implements Comparator<A> {

    @Override
    public int compare(A o1, A o2) {
        return (int)(o1.sore - o2.sore);
    }
}
class NameComparator implements Comparator<A> {


    @Override
    public int compare(A o1, A o2) {
        return (o1.name.compareTo(o2.name));
    }


}
public class Demo1 {

    public static void sort(Comparable[] array) {
        for (int i = 0; i < array.length-1; i++) {
            for (int j = 0; j < array.length-1-i; j++) {
                if(array[j].compareTo(array[j+1]) > 0) {
                    Comparable tmp = array[j+1];
                    array[j+1] = array[j];
                    array[j] = tmp;
                }
            }
        }

    }

    public static void main(String[] args) {
        A[] as = new A[3];
        as[0] = new A("张三",12,87.23);
        as[1] = new A("李四",18,69.50);
        as[2] = new A("王五",19,67.50);
        sort(as);
        System.out.println(Arrays.toString(as));
    }
    public static void main2(String[] args) {
        A a1 = new A("张三",12,87.23);
        A a2 = new A("李四",18,69.50);




        AgeComparator ageComparator = new AgeComparator();
        NameComparator nameComparator = new NameComparator();
        int ret1 = nameComparator.compare(a1,a2);
        int ret = ageComparator.compare(a1,a2);
        System.out.println(ret);
        System.out.println(ret1);

    }


    public static void main1(String[] args) {
        A a1 = new A("张三",12);
        A a2 = new A("李四",18);
        if(a1.compareTo(a2) > 0) {
            System.out.println("a1 > a2");
        }else if(a1.compareTo(a2) == 0) {
            System.out.println("a1 == a2");
        }else {
            System.out.println("a1 < a2");
        }

    }
}
